<template>
  <div class="row">
    <el-cascader
      v-if="show"
      v-model="region"
      :size="size"
      :disabled="compile"
      class="select"
      collapse-tags
      clearable
      :props="cityProps"
      @change="(val)=>changeRegion(val)"
    />
  </div>
</template>

<script>
import { regionList } from '@/api/user';
export default {
  props: {
    detail: {
      type: Array,
      default() {
        return [];
      }
    },
    size: {
      type: String,
      default: 'small'
    },
    compile: {
      type: Boolean,
      default: false
    },
    second: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: true,
      region: [],
      cityProps: {
        label: 'name',
        value: 'name',
        // multiple: true,
        lazy: true,
        emitPath: true,
        lazyLoad: this.lazyLoad
      }
    };
  },
  watch: {
    detail: {
      handler(val) {
        this.show = false;
        this.region = val;
        setTimeout(() => {
          this.show = true;
        }, 100);
      }
    }
  },
  mounted() {
    this.region = this.detail;
  },
  methods: {
    // 获取省市区
    async lazyLoad(node, resolve) {
      let list = [];
      let stop_level = this.second ? 1 : 2;
      let level = node.level;
      let pid = node.level ? node.data.id : 0;
      let callback = () => {
        resolve(
          (list || []).map(ele => {
            return Object.assign(ele, {
              leaf: level >= stop_level
            });
          })
        );
      };
      const res = await regionList({ pid: pid });
      list = res ? res.data : [];
      callback();
    },
    changeRegion() {
      this.$emit('getRegion', this.region);
    }
  }
};
</script>

<style scoped>
.select {
  flex: 1;
}
</style>
